package webgamemaker.Common;

import java.util.Map;

import com.google.gwt.widgetideas.graphics.client.GWTCanvas;


public class BaseTile implements Tile
{
	public TileSet tileset;
	public int x, y;
	public int width, height;
	
	public BaseTile(TileSet tileset, int x, int y, int width, int height)
	{
		this.tileset = tileset;
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}
	
	public void draw(Map<String, Object> param) 
	{
		int srcX = 0, srcY = 0;
		int srcWidth, srcHeight;
		int x, y;
		int width, height;
		if(!param.containsKey("context"))
			throw new RuntimeException("contexte d'affichage non fourni");
		if(!param.containsKey("x") || !param.containsKey("y"))
			throw new RuntimeException("position du tile non fourni");
		GWTCanvas context = (GWTCanvas) param.get("context");
		if(param.containsKey("srcX"))
			srcX = (Integer)param.get("srcX");
		if(param.containsKey("srcY"))
			srcY = (Integer)param.get("srcY");
		if(param.containsKey("srcWidth"))
			srcWidth = (Integer)param.get("srcWidth");
		else srcWidth = this.width-srcX;
		if(param.containsKey("srcHeight"))
			srcHeight = (Integer)param.get("srcHeight");
		else srcHeight = this.height-srcY;
		srcX += this.x;
		srcY += this.y;
		x = (Integer)param.get("x");
		y = (Integer)param.get("y");
		if(param.containsKey("width"))
			width = (Integer)param.get("width");
		else width = srcWidth;
		if(param.containsKey("height"))
			height = (Integer)param.get("height");
		else height = srcHeight;
		boolean mirror = false;
		if(param.containsKey("mirrorX") && ((Boolean)param.get("mirrorX"))==true)
		{
			mirror = true;
			context.saveContext();
			context.scale(-1, 1);
			context.translate(-(2*x+width), 0);
		}
		
		if(param.containsKey("mirrorY") && ((Boolean)param.get("mirrorY"))==true)
		{
			if(!mirror)
			{
				mirror = true;
				context.saveContext();
			}
			context.scale(1, -1);
			context.translate(0, -(2*y+height));
		}
		context.drawImage(tileset.image, srcX, srcY, srcWidth, srcHeight, x, y, width, height);
		if(mirror)
			context.restoreContext();
	}

	public int[] getSize() 
	{
		int tab[] = new int[2];
		tab[0] = width;
		tab[1] = height;
		return tab;
	}

}
